package com.integral.biz.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.integral.biz.IDeclarationBiz;
import com.integral.constant.DeclarationConstant;
import com.integral.constant.OrderConstant;
import com.integral.constant.UserRelationConstant;
import com.integral.entity.Balance;
import com.integral.entity.Bank;
import com.integral.entity.BankExchangeRate;
import com.integral.entity.BankType;
import com.integral.entity.Declaration;
import com.integral.entity.Order;
import com.integral.entity.User;
import com.integral.entity.UserRelation;
import com.integral.service.BalanceService;
import com.integral.service.BankExchangeRateService;
import com.integral.service.BankService;
import com.integral.service.BankTypeService;
import com.integral.service.DeclarationService;
import com.integral.service.OrderService;
import com.integral.service.UserRelationService;
import com.integral.service.UserService;
import com.integral.service.UserTypeService;
import com.integral.vo.BankExchangeRateVo;
import com.integral.vo.DeclarationVo;
import com.integral.vo.UserRelationVo;
import com.integral.vo.UserVo;

/**
 * @Description: 报单表BIZ实现类
 * @author zhaofan
 * @date 2018年05月08日 上午01:56:20
 */
@Service("declarationBiz")
public class DeclarationBiz implements IDeclarationBiz {
	
	protected final Log logger = LogFactory.getLog(getClass());
	/**
	 * 注入报单表Service
	 */
	@Resource
	private DeclarationService declarationService;

	@Resource
	private UserService userService;
	@Resource
	private UserTypeService userTypeService;
	@Resource
	private BankService bankService;
	@Resource
	private BankTypeService bankTypeService;
	//结算关系
	@Resource
	private UserRelationService userRelationService;
	//银行汇率
	@Resource
	private BankExchangeRateService bankExchangeRateService;
	//用户余额表
	@Resource
	private BalanceService balanceService;
	//订单
	@Resource
	private OrderService orderService;
	
	/**
	 * @Description: 新增报单表
	 * @param declaration
	 * @return 受影响行数
	 * @author zhaofan
	 * @date 2018年05月08日 上午01:56:20
	 */
	public int addDeclaration(Declaration declaration) {
		return declarationService.addDeclaration(declaration);
	}
	
	/**
	 * @Description: 修改报单表
	 * @param declaration 报单表
	 * @return 受影响行数
	 * @author zhaofan
	 * @date 2018年05月08日 上午01:56:20
	 */
	public int updateDeclaration(Declaration declaration) {
		return declarationService.updateById(declaration);
	}
	
	/**
	 * @Description: 删除报单表
	 * @param id 主键
	 * @return 受影响行数
	 * @author zhaofan
	 * @date 2018年05月08日 上午01:56:20
	 */
	public int deleteDeclaration(Long id) {
		return declarationService.deleteById(id);
	}
	
	/**
	 * @Description: 根据ID查询报单表
	 * @param id 主键
	 * @return 报单表
	 * @author zhaofan
	 * @date 2018年05月08日 上午01:56:20
	 */
	public Declaration findById(Long id) {
		return declarationService.findById(id);
	}
	
	/**
	 * 查询报单信息总记录数
	 * @param declarationVo
	 * @return
	 */
	public Long findDeclarationCount(DeclarationVo declarationVo){
		return declarationService.findDeclarationCount(declarationVo);
	}
	/**
	 * 查询报单信息列表
	 * @param declarationVo
	 * @return
	 */
	public List<DeclarationVo> findDeclaration(DeclarationVo declarationVo){
		List<DeclarationVo> list = declarationService.findDeclaration(declarationVo);
		for (DeclarationVo declarationVo2 : list) {
			//编码转换
			codeTransform(declarationVo2);
		}
		return list;
	}
	
	//编码转换
	private void codeTransform(DeclarationVo declarationVo){
		//银行产品名称编码转换
		if(!StringUtils.isEmpty(declarationVo.getBankTypeCode())){
			BankType bankType = bankTypeService.findByBankTypeCode(declarationVo.getBankTypeCode());
			if(null != bankType){
				declarationVo.setBankTypeName(bankType.getBankTypeName());
			}
		}
		//用户名称
		if(!StringUtils.isEmpty(declarationVo.getUserOpenid())){
			UserVo user = userService.findByUserOpenid(declarationVo.getUserOpenid());
			if(null != user){
				declarationVo.setUserName(user.getUserName());
			}
		}
	}
	/**
	 * 审核报单
	 * @param declarationVo
	 */
	@Override
	public int auditDeclaration(DeclarationVo declarationVo){
		if(StringUtils.isEmpty(declarationVo.getBankTypeCode()) || StringUtils.isEmpty(declarationVo.getUserOpenid())){
			return -1;
		}
		//获取银行产品信息
		BankType bankType = bankTypeService.findByBankTypeCode(declarationVo.getBankTypeCode());
		if(null == bankType){
			logger.error("审核报单异常-基础信息不全返回-1");
			return -1;
		}
		//获取银行信息
		Bank bank = bankService.findByBankCode(bankType.getBankCode());
		//获取用户信息
		UserVo user = userService.findByUserOpenid(declarationVo.getUserOpenid());
		if(null == bank || null == user){
			logger.error("审核报单异常-基础信息不全返回-1");
			return -1;
		}
		//设置状态-已审核
		declarationVo.setStatus(DeclarationConstant.STATUS_SUCCESS);
		//修改报单状态
		int t = declarationService.updateStatus(declarationVo);
		logger.warn("审核报单-修改报单对象:【"+JSON.toJSON(declarationVo)+"】受影响记录数:"+t);
		if(t > 0){
			//银行汇率
			BankExchangeRate bankExchangeRate = findBankExchangeRate(bank.getBankCode(), user.getUserTypeCode());
			if(null == bankExchangeRate){
				logger.error("审核报单异常-找不到银行汇率-2【"+bank.getBankCode()+user.getUserTypeCode()+"】");
				return -2;
			}
			//获取兑换金额
			//获取报单数量
			Integer be = declarationVo.getDeclarationNum();
			if(be == null || be == 0){
				be = 1;
			}
			BigDecimal money = bankType.getCounterPurchase().multiply(bankExchangeRate.getBankExchangeRate());
			money = money.multiply(new BigDecimal(be));
			money = money.setScale(2,BigDecimal.ROUND_HALF_UP);
			//修改余额(增加余额)
			int m = balanceCharge(user.getUserCode(), money);
			if(m == -1){
				logger.error("审核报单异常-找不到余额记录-3【"+user.getUserCode()+"】");
				return -3;
			}
			//判断是否存在上级用户
			if(!StringUtils.isEmpty(user.getUserSuperiorCode())){
				//查询上级用户
				User superiorUser = userService.findByCode(user.getUserSuperiorCode());
				if(null == superiorUser){
					logger.error("审核报单异常-找不到上级用户-4【"+user.getUserSuperiorCode()+"】");
					return -4;
				}
				//获取结算关系
				UserRelation userRelation = findRelationService(superiorUser.getUserTypeCode(), user.getUserTypeCode());
				if(null == userRelation){
					logger.error("审核报单异常-找不到结算关系-5【"+superiorUser.getUserTypeCode()+","+user.getUserTypeCode()+"】");
					return -5;
				}
				//上级用户金额
				BigDecimal superMoney = new BigDecimal(0);
				//判断是否为利差
				if(userRelation.getRelationshipClearing() == UserRelationConstant.CLEARING_INTERSET){
					//利差
					superMoney = calculateMoney(money, bankType.getCounterPurchase(), superiorUser.getUserTypeCode(), bank.getBankCode(),be);
				}else{
					//佣金
					superMoney = userRelation.getMoney();
				}
				superMoney = superMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
				Order order = new Order();
				String orderNo = "D"+com.integral.util.StringUtils.getRandomStringByLength(5)+new Date().getTime();
				//订单编号
				order.setOrderNo(orderNo);
				//银行编码
				order.setBankCode(bank.getBankCode());
				//银行产品
				order.setBankTypeCode(bankType.getBankTypeCode());
				//兑换积分
				//order.setExchangeIntegral(bankType.getIntegralNo());
				//报单ID
				order.setDeclarationId(declarationVo.getId());
				//金额
				order.setExchangeMoney(superMoney);
				//订单状态
				order.setOrderStatus(OrderConstant.ORDER_STATUS_SUCCESS);
				//订单类型
				order.setOrderType(OrderConstant.ORDER_TYPE_RELATION);
				//用户编码
				order.setUserCode(superiorUser.getUserCode());
				//结算关系ID
				order.setUserRelationId(userRelation.getId());
				//新增订单
				orderService.addOrder(order);

				//上级用户返利
				balanceCharge(superiorUser.getUserCode(), superMoney);
				
			}
			//报单成功-产生订单信息
			Order declarationOrder = new Order();
			String orderNo = "D"+com.integral.util.StringUtils.getRandomStringByLength(5)+new Date().getTime();
			//订单编号
			declarationOrder.setOrderNo(orderNo);
			//银行编码
			declarationOrder.setBankCode(bank.getBankCode());
			//银行产品
			declarationOrder.setBankTypeCode(bankType.getBankTypeCode());
			//兑换积分
			declarationOrder.setExchangeIntegral(bankType.getIntegralNo());
			//金额
			declarationOrder.setExchangeMoney(money);
			//订单状态
			declarationOrder.setOrderStatus(OrderConstant.ORDER_STATUS_SUCCESS);
			//订单类型
			declarationOrder.setOrderType(OrderConstant.ORDER_TYPE_INTEGRAL);
			//用户编码
			declarationOrder.setUserCode(user.getUserCode());
			//报单ID
			declarationOrder.setDeclarationId(declarationVo.getId());
			//汇率ID
			declarationOrder.setExchangeRateId(bankExchangeRate.getId());
			//新增订单
			orderService.addOrder(declarationOrder);
		}
		return 1;
	}
	/**
	 * 计算利差
	 * @param money 原始金额
	 * @param counterPurchase 回购价格
	 * @param userTypeCode 用户类别
	 * @param bankCode 银行编码
	 * @param be 报单数量
	 * @return 利差金额
	 */
	private BigDecimal calculateMoney(BigDecimal money,BigDecimal counterPurchase,String userTypeCode,String bankCode,Integer be){
		//查询银行汇率
		BankExchangeRate bankExchangeRate = findBankExchangeRate(bankCode, userTypeCode);
		//获取金额
		BigDecimal calculateMoney = counterPurchase.multiply(bankExchangeRate.getBankExchangeRate());
		calculateMoney = calculateMoney.multiply(new BigDecimal(be));
		return calculateMoney.subtract(money);
	}
	
	/**
	 * 查询结算关系
	 * @param superiorTypeCode	上级类别
	 * @param subordinateTypeCode 下级类别
	 * @return 结算关系
	 */
	private UserRelation findRelationService(String superiorTypeCode,String subordinateTypeCode){
		UserRelationVo userRelationVo = new UserRelationVo();
		//上级类别
		userRelationVo.setSuperiorTypeCode(superiorTypeCode);
		//下级类别
		userRelationVo.setSubordinateTypeCode(subordinateTypeCode);
		userRelationVo.setDeleteFlag(0);
		userRelationVo.setEnabledFalse("1");
		return userRelationService.findByUserRelation(userRelationVo);
	}
	//获取银行汇率
	private BankExchangeRate findBankExchangeRate(String bankCode,String userTypeCode){
		BankExchangeRateVo bankExchangeRateVo = new BankExchangeRateVo();
		bankExchangeRateVo.setBankCode(bankCode);
		bankExchangeRateVo.setUserTypeCode(userTypeCode);
		bankExchangeRateVo.setDeleteFlag(0);
		return bankExchangeRateService.findByBankExchangeRate(bankExchangeRateVo);
	}
	/**
	 * 修改余额
	 * @param userCode
	 * @param userMoney
	 * @return 受影响记录数（-1:找不到余额记录）
	 */
	private int balanceCharge(String userCode,BigDecimal money){
		//查询余额
		Balance queryBalance = balanceService.findByUserCode(userCode);
		if(null == queryBalance){
			return -1;
		}
		Balance balance = new Balance();
		balance.setId(queryBalance.getId());
		balance.setUserMoney(money.add(queryBalance.getUserMoney()));
		return balanceService.updateById(balance);
	}
	/**
	 * 驳回报单
	 */
	public int auditFile(DeclarationVo declarationVo){
		//设置状态-已审核
		declarationVo.setStatus(DeclarationConstant.STATUS_FAIL);
		//修改报单状态
		return declarationService.updateStatus(declarationVo);
	}
	/**
	 * 人工报单
	 * @param declarationVo
	 * @return
	 */
	@Override
	public int artificialDeclaration(DeclarationVo declarationVo){
		Declaration declaration = new Declaration();
		//用户编码转换用户唯一标识
		if(!StringUtils.isEmpty(declarationVo.getUserCode())){
			User user = userService.findByCode(declarationVo.getUserCode());
			if(null != user){
				declaration.setUserOpenid(user.getUserOpenid());
			}else{
				return -1;
			}
		}
		//银行产品
		declaration.setBankTypeCode(declarationVo.getBankTypeCode());
		//兑换编码
		declaration.setDeclarationExchangeCode(declarationVo.getDeclarationExchangeCode());
		//备注信息
		declaration.setRemark(declarationVo.getRemark());
		//状态-未审核
		declaration.setStatus(DeclarationConstant.STATUS_UNTREATED);
		//上传截图
		declaration.setDeclarationImg(declarationVo.getDeclarationImg());
		int result = declarationService.addDeclaration(declaration);
		return result;
	}
}